<?php


namespace app\controller\v1;


use app\model\CommodityGoods;
use app\model\CommodityOrder;
use app\model\CommoditySpec;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\Request;

/**
 * 购物车
 * Class Cart
 * @package app\controller\v1
 */
class Cart
{

    /**
     * Cart constructor.
     * @param Request $request
     */
    public function __construct(Request $request)
    {
        $this->data = $request->data;
        $this->user = $request->user;
        $this->goods = $request->goods;
    }


    /**
     * 购物车列表
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function cartList()
    {
        $this->data['province'] = '';
        return app()->make(CommodityOrder::class)->cartList($this->data);
    }

    /**
     * 添加购物车
     * @return mixed
     */
    public function addCart()
    {
        RedisLock('CartLock_' . $this->user->id);
        try {
            $goods_spe = app()->make(CommoditySpec::class)->lock(true)->where(['goods_id' => $this->goods['id'], 'goods_spec_id' => $this->data['goods_spec_id']])->find();
            if (!$goods_spe) {
                return app('json')->json_error('此商品规格不存在');
            }
            if ($this->data['num'] > $goods_spe->stock) {
                return app('json')->json_error('库存不足');
            }
            if ($goods_spe->stock - $this->data['num'] < 0) {
                return app('json')->json_error('库存不足');
            }
            $arr = \app\services\Cart::getInstance()->addCart($this->user->id, $goods_spe, $this->data['num']);
            if ($arr['code'] == 0) {
                return app('json')->json_error('数量错误');
            }
            return app('json')->json_success('成功');
        } catch (\Exception $exception) {
            return app('json')->json_error('收藏失败' . $exception->getMessage());
        }
    }


    /**
     * 清空购物车
     * @return mixed
     */
    public function cartDel()
    {
        RedisLock('CartLock_' . $this->user->id);
        try {
            switch ($this->data['type']) {
                case 1:
                    \app\services\Cart::getInstance()->cartDelOne($this->user->id, $this->data['goods_spec_id']);
                    break;
                case 2:
                    \app\services\Cart::getInstance()->cartDelAll($this->user->id);
                    break;
            }
            return app('json')->json_success('成功');
        } catch (\Exception $exception) {
            return app('json')->json_error('删除失败' . $exception->getMessage());
        }
    }


}


